package qs.openxt.libs.update;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import qs.openxt.libs.App;
import qs.openxt.libs.R;
import qs.openxt.libs.activity.OpenxtActivity;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.remoting.Download;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/4/6.
 */
public class AutoUpdateEx {
    private Context context;
    private String updateUrl;
    private Object data;
    private boolean isShowWait;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:{

                    break;
                }
                default:
                    break;
            }
        };
    };

    public AutoUpdateEx(Context context, String updateUrl, Object data, boolean isShowWait){
        this.context = context;
        this.updateUrl = updateUrl;
        this.isShowWait = isShowWait;
        this.data = data;
    }

    public void update(){
        if(!ActivityUtil.isNetworkAvailable(context)){
            Toast.makeText(context, context.getString(R.string.isNetworkAvailable), Toast.LENGTH_LONG).show();
            return;
        }

        if(isShowWait)
            Wait.sharedInstance().start(context, "正在获取最新版本信息..., 请稍候");

        RequestParams requestParams = new RequestParams(updateUrl);
        if (data instanceof JSONObject) {
            Map<String, String> param = new HashMap<String, String>();
            JSONObject $data = (JSONObject) data;
            Iterator it = $data.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                requestParams.addQueryStringParameter(key, $data.getString(key));
            }
        }else{
            String param = data.toString();
            String[] params = param.split("\\&");
            for(int i = 0, j = params.length; i < j; i++){
                String[] ss = params[i].split("\\=");
                requestParams.addQueryStringParameter(ss[0], ss[1]);
            }
        }
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                doSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                doError(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void doSuccess(String reVal) {
        if(isShowWait)
            Wait.sharedInstance().stop();

        try {
            String app_path = Utils.getLocalStorage(context, App.UPDATE_APP);
            if(!StringUtil.isNull(app_path)) {
                File f = new File(app_path);
                if (f.exists())
                    f.delete();
            }

            //解析
            JSONObject json = JSON.parseObject(reVal);
            String type = json.getString("type");
            if("1".equals(type)){
                final JSONObject data = json.getJSONObject("data");
                String NeetUpdate = data.getString("NeetUpdate");
                if("true".equals(NeetUpdate)){//强制更新
                    String tip = "检测到新版本，不更新将无法进入？";
                    ActivityUtil.showConfirmDialog(context, tip, "更新", "退出", new ConfirmDialogListener() {
                        @Override
                        public void onOK() {
                            doUpdateApp(data.getString("Url"));
                        }

                        @Override
                        public void onCancel() {
                            if(context instanceof OpenxtActivity){
                                ((OpenxtActivity)context).finish();
                            }
                        }
                    });
                }else if("false".equals(NeetUpdate)){//强制更新
                    String tip = "检测到新版本，是否更新？";
                    ActivityUtil.showConfirmDialog(context, tip, "更新", "不更新", new ConfirmDialogListener() {
                        @Override
                        public void onOK() {
                            doUpdateApp(data.getString("Url"));
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                }else if(isShowWait)
                    Toast.makeText(context, "版本已最新", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(context, json.getString("msg"), Toast.LENGTH_LONG).show();
            }
        }catch (Exception e){

        }
    }

    public void doError(String msg) {
        if(isShowWait)
            Wait.sharedInstance().stop();
        Toast.makeText(context, "通讯失败，超时或者网络不通", Toast.LENGTH_LONG).show();
    }

    private void doUpdateApp(String uri){
        Download download = new Download(context, uri, new Download.OnActionListener() {
            @Override
            public void onActionCompleted(String path) {
                Utils.setLocalStorage(context, App.UPDATE_APP, path);
                installApk(path);
            }

            @Override
            public void onActionError(String error) {
                Toast.makeText(context, error, Toast.LENGTH_LONG).show();
            }
        });
        download.doRequest();
    }

    private void installApk(String apkfile){
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(apkfile)), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

            if(context instanceof OpenxtActivity){
                ((OpenxtActivity)context).finish();
            }
        }catch (Exception e){
        }
    }
}
